package com.example.yangxu0703.thundermapclient.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.PoiInputItemWidget;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.activity.MainActivity;
import com.example.yangxu0703.thundermapclient.activity.SearchPoiActivity;
import com.example.yangxu0703.thundermapclient.adapter.SearchResultAdapter;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


public class DirectinfoFragment extends Fragment implements AMapLocationListener, LocationSource, TextWatcher, Inputtips.InputtipsListener, PoiSearch.OnPoiSearchListener {

    public static NaviLatLng start_dir = new NaviLatLng();
    public static NaviLatLng end_dir = new NaviLatLng();
    public static String name_city;
    public AMapLocationClient mlocationClient;
    public AMapLocationClientOption mLocationOption = null;
    public View view;
    private OnLocationChangedListener listener;
    private AMap mAmap;
    public MapView naviView;
    private MyLocationStyle myLocationStyle;
    private AutoCompleteTextView mKeywordText;
    private static final String TAG = "Map_Location";
    private BitmapDescriptor start, end;
    private MarkerOptions startoption, endoption;
    public static String destination="";

    @SuppressLint("HandlerLeak")
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1){
                case 1:
                    startoption.title("我的位置").position(new LatLng(start_dir.getLatitude(), start_dir.getLongitude())).icon(start);
                    Marker marker = mAmap.addMarker(startoption);
                    break;
            }
        }
    };


    private List<Tip> mCurrentTipList;
    private SearchResultAdapter resultAdapter;
    private ListView resultList;
    private Poi selectedPoi;
    private PopupWindow popupWindow;
    private int pointType= -1;
    private  Poi poi;
    private  InputMethodManager imm ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_direct_info_, container, false);
        view.requestFocus();
        naviView = view.findViewById(R.id.navi_view_loc);

        mKeywordText = view.findViewById(R.id.search_input);
        mKeywordText.addTextChangedListener(DirectinfoFragment.this);
        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mKeywordText.getWindowToken(), 0);
        mKeywordText.requestFocus();

        naviView.onCreate(savedInstanceState);
        mAmap = naviView.getMap();
        startoption = new MarkerOptions();
        endoption = new MarkerOptions();
        setupMap();
        popupWindow = new PopupWindow(getActivity());
        return view;
    }

    public void resetMap(){
        mAmap.clear();
        startoption.title("我的位置").position(new LatLng(start_dir.getLatitude(), start_dir.getLongitude())).icon(start);
        Marker marker = mAmap.addMarker(startoption);
        mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(start_dir.getLatitude(), start_dir.getLongitude())));
    }

    public void setupMap() {
        start = BitmapDescriptorFactory.fromResource(R.drawable.start);
        end = BitmapDescriptorFactory.fromResource(R.drawable.end);

        if (mAmap != null) {
            mAmap.setLocationSource(this);
            mAmap.getUiSettings().setLogoBottomMargin(-100);
            mAmap.getUiSettings().setZoomControlsEnabled(false);
            mAmap.getUiSettings().setMyLocationButtonEnabled(false);
            mAmap.setMyLocationEnabled(true);
            mAmap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
            mAmap.moveCamera(CameraUpdateFactory.zoomTo(20));
        }
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        mAmap.setMyLocationStyle(myLocationStyle);
        mAmap.setMyLocationEnabled(true);
        myLocationStyle.showMyLocation(true);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.i(TAG,"onLocationChanged");
        if (aMapLocation != null) {
            StringBuffer sb = new StringBuffer();
            //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
            if (aMapLocation.getErrorCode() == 0) {
                listener.onLocationChanged(aMapLocation);
                start_dir.setLongitude(aMapLocation.getLongitude());
                start_dir.setLatitude(aMapLocation.getLatitude());
                name_city = aMapLocation.getCity();

                Log.i(TAG, "" + aMapLocation.getLongitude() + "--" + aMapLocation.getLatitude());
                handler.sendEmptyMessage(1);
            } else {
                //定位失败
                sb.append("定位失败" + "\n");
                sb.append("错误码:" + aMapLocation.getErrorCode() + "\n");
                sb.append("错误信息:" + aMapLocation.getErrorInfo() + "\n");
                sb.append("错误描述:" + aMapLocation.getLocationDetail() + "\n");
            }
            Log.i(TAG, sb.toString());
        } else {
            Log.i(TAG, "location occuer failed!!!");
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        Log.i(TAG,"activate");
        listener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setNeedAddress(true);
            mLocationOption.setOnceLocation(true);
            AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.setLocationListener(this);
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        listener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

/*    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        Log.i(TAG,"Map connect!");
        if (hasFocus){
            Intent intent =new Intent(getActivity(), SearchPoiActivity.class);
            intent.putExtra("pointType",0);
            startActivityForResult(intent,100);
        }
    }*/

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("onActivityResult", "data back!");

        if (data != null) {
            Bundle bundle = data.getExtras();
            Poi poi = (Poi) bundle.get("poi");
            end_dir.setLongitude(poi.getCoordinate().longitude);
            end_dir.setLatitude(poi.getCoordinate().latitude);
            Log.i(TAG, "--" + poi.getName() + "--" + poi.getCoordinate().longitude + "" + poi.getCoordinate().latitude);
            // editText.setText("" + poi.getName());

            endoption.title("我的位置").position(new LatLng(end_dir.getLatitude(), end_dir.getLongitude())).icon(end);
            Marker marker = mAmap.addMarker(endoption);
            mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(poi.getCoordinate().latitude, poi.getCoordinate().longitude)));

            Log.i(TAG, start_dir.getLatitude() + "====" + start_dir.getLongitude());
            Log.i(TAG, end_dir.getLatitude() + "====" + end_dir.getLongitude());

            //切换fragment
            Message message = new Message();
            Bundle b = new Bundle();
            b.putString("start", start_dir.getLatitude() + "%" + start_dir.getLongitude());
            b.putString("end", end_dir.getLatitude() + "%" + end_dir.getLongitude());
            message.setData(b);
            message.arg1 = 1;
        } else {
            Toast.makeText(getActivity(), "请重新选择地点！", Toast.LENGTH_SHORT).show();
        }

        ((MainActivity) getActivity()).handler.sendEmptyMessage(1);
    }

    @Override
    public void onResume() {
        super.onResume();
        view.requestFocus();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            Log.i(TAG,"beforeTextChanged--"+ s);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        View viewContents = getActivity().getLayoutInflater().inflate(R.layout.position_popu_layout, null, false);
        resultList = viewContents.findViewById(R.id.res_position);
        resultList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                imm.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
                Tip tip = (Tip) parent.getItemAtPosition(position);
                destination=tip.getName();

                selectedPoi = new Poi(tip.getName(), new LatLng(tip.getPoint().getLatitude(), tip.getPoint().getLongitude()), tip.getPoiID());
                if (!TextUtils.isEmpty(selectedPoi.getPoiId())) {
                    PoiSearch.Query query = new PoiSearch.Query(selectedPoi.getName(), "", name_city);
                    query.setDistanceSort(false);
                    query.requireSubPois(true);
                    PoiSearch poiSearch = new PoiSearch(getActivity().getApplicationContext(), query);
                    poiSearch.setOnPoiSearchListener(DirectinfoFragment.this);
                    poiSearch.searchPOIIdAsyn(selectedPoi.getPoiId());
                }
                Log.i(TAG,"onTextChanged--"+tip.getName()+selectedPoi.getCoordinate().longitude+"--"+selectedPoi.getCoordinate().latitude);
                popupWindow.dismiss();
            }
        });
        popupWindow.setContentView(viewContents);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.showAsDropDown(mKeywordText);
        String newText = s.toString().trim();
        if (!TextUtils.isEmpty(newText)) {
            InputtipsQuery inputquery = new InputtipsQuery(newText, name_city);
            Inputtips inputTips = new Inputtips(getActivity().getApplicationContext(), inputquery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        }
        Log.i(TAG,"---"+s+popupWindow.isShowing());

    }

    @Override
    public void afterTextChanged(Editable s) {
        Log.i(TAG,"afterTextChanged--"+s+"------"+ s.toString().equals(""));
        if (s.toString().equals("") && popupWindow.isShowing()){
            popupWindow.dismiss();
            Log.i(TAG ,"dismiss");
        }
    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        try {
            if (rCode == 1000) {
                mCurrentTipList = new ArrayList<Tip>();
                for (Tip tip : tipList) {
                    if (null == tip.getPoint()) {
                        continue;
                    }
                    mCurrentTipList.add(tip);
                }
                if (null == mCurrentTipList || mCurrentTipList.isEmpty()) {
                    /*tvMsg.setText("抱歉，没有搜索到结果，请换个关键词试试");
                    tvMsg.setVisibility(View.VISIBLE);
                    resultList.setVisibility(View.GONE);*/
                } else {
                    resultList.setVisibility(View.VISIBLE);
                    resultAdapter = new SearchResultAdapter(getActivity().getApplicationContext(), mCurrentTipList);
                    resultList.setAdapter(resultAdapter);
                    resultAdapter.notifyDataSetChanged();
                }
            } else {
                /*tvMsg.setText("出错了，请稍后重试");
                tvMsg.setVisibility(View.VISIBLE);*/
            }
        } catch (Throwable e) {
         /*   tvMsg.setText("出错了，请稍后重试");
            tvMsg.setVisibility(View.VISIBLE);*/
        }

    }


    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int errorCode) {
        try {
            LatLng latLng = null;
            int code = 0;
            if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
                if (poiItem == null) {
                    return;
                }
                LatLonPoint exitP = poiItem.getExit();
                LatLonPoint enterP = poiItem.getEnter();
                if (pointType == PoiInputItemWidget.TYPE_START) {
                    code = 100;
                    if (exitP != null) {
                        latLng = new LatLng(exitP.getLatitude(), exitP.getLongitude());
                    } else {
                        if (enterP != null) {
                            latLng = new LatLng(enterP.getLatitude(), enterP.getLongitude());
                        }
                    }
                }
                if (pointType == PoiInputItemWidget.TYPE_DEST) {
                    code = 200;
                    if (enterP != null) {
                        latLng = new LatLng(enterP.getLatitude(), enterP.getLongitude());
                    }
                }
            }

            if (latLng != null) {
                poi = new Poi(selectedPoi.getName(), latLng, selectedPoi.getPoiId());
            } else {
                poi = selectedPoi;
            }
            Log.i(TAG,""+poi.getName()+"--"+poi.getCoordinate().latitude+"---"+poi.getCoordinate().longitude);

        } catch (Throwable e) {
            e.printStackTrace();
        }

        end_dir.setLongitude(poi.getCoordinate().longitude);
        end_dir.setLatitude(poi.getCoordinate().latitude);

        endoption.title("我的位置").position(new LatLng(end_dir.getLatitude(), end_dir.getLongitude())).icon(end);
        Marker marker = mAmap.addMarker(endoption);
        mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(poi.getCoordinate().latitude, poi.getCoordinate().longitude)));

        Log.i(TAG, start_dir.getLatitude() + "====" + start_dir.getLongitude());
        Log.i(TAG, end_dir.getLatitude() + "====" + end_dir.getLongitude());

        naviView.setVisibility(View.INVISIBLE);
        //切换fragment
        Message message = new Message();
        Bundle b = new Bundle();
        b.putString("start", start_dir.getLatitude() + "%" + start_dir.getLongitude());
        b.putString("end", end_dir.getLatitude() + "%" + end_dir.getLongitude());
        message.setData(b);
        message.arg1 = 1;
        ((MainActivity) getActivity()).handler.sendEmptyMessage(1);
    }


}
